package com.googlecode.cswish.security.type;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.googlecode.cswish.security.auth.Parameter;


/**
 * @author Jerry.Feng Date: Nov 8, 2007 2:04:16 PM
 * @version $id: $
 */
public class Condition {

	public static final Condition TRUE = new Condition(){
		public boolean caculate(Parameter parameter) {
			return true;
		}
	};
	
	private List expressList = new ArrayList();
	
	public boolean caculate(Parameter parameter) {
		for (Iterator iter = expressList.iterator(); iter.hasNext();) {
			Expression[] expressions = (Expression[]) iter.next();
			
			boolean ret = true;
			for (int i = 0; ret && i < expressions.length; i++) {
				ret &= expressions[i].execute(parameter);
			}
			
			if (ret) {
				return ret;
			}
		}
		
		return false;
	}
	
	public void addExpression(Expression[] expression) {
		// TODO: combine the expression?
		expressList.add(expression);
	}
	
	public Condition combine(Condition condition) {
		if (this == Condition.TRUE || condition == Condition.TRUE) {
			return Condition.TRUE;
		}
		
		// TODO: call addExpression insteadof new ArrayList
		List expression = new ArrayList(this.expressList.size()
				+ condition.expressList.size());
		
		expression.addAll(this.expressList);
		expression.addAll(condition.expressList);
		
		Condition combineCond = new Condition();
		combineCond.expressList = expression;
		return combineCond;
	}
}
